/**
 * @description 补零
 * @param {Object} number
 */
export function addZero(number) {
	if (!number || number > 9) return number;
	return `0${number}`;
}

/**
 * @description 获取当前年月日
 */
export function getCurYMD() {
	const date = new Date();
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	return `${year}${addZero(month)}${addZero(day)}`;
}

/**
 * 获取当前登录用户
 */
export function getUser() {
	const userInfo = uni.getStorageSync('uni-id-pages-userInfo');
	return userInfo?._id;
}

/**
 * 上传文件到指定目录
 */
export async function uploadFileToDir({ tempFiles, tempFilePaths }, dir, uploadedCallback, progressCallback = null) {
	let size = 0;
	const { name: filename } = tempFiles[0];
	const [name, extname] = filename.split('.');
	const uploadRes = await uniCloud.uploadFile({
		filePath: tempFilePaths[0],
		cloudPath: `${dir}/${name}_${Date.now()}.${extname}`,
		onUploadProgress: (progressEvent) => {
			const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
			progressCallback?.(percentCompleted);
			size = progressEvent.total;
		}
	});
	const fileRes = await uniCloud.getTempFileURL({
		fileList: [uploadRes.fileID]
	});
	if (fileRes.fileList?.length) {
		const file = fileRes.fileList[0];
		uploadedCallback({
			...file,
			name,
			url: file.tempFileURL,
			size,
			extname,
			fileType: 'image'
		});
	}
}

export async function multiplyUploadFileToDir({ tempFiles, tempFilePaths }, dir, uploadedCallback, progressCallback = null) {
	const uploadResList = await Promise.all(
		tempFiles.map((item, index) => {
			const { name: filename } = item;
			const [name, extname] = filename.split('.');
			tempFiles[index].extname = extname;
			tempFiles[index].filename = name;
			return uniCloud.uploadFile({
				filePath: tempFilePaths[index],
				cloudPath: `${dir}/${name}_${Date.now()}.${extname}`
			});
		})
	);
	if (uploadResList?.length === tempFiles.length) {
		progressCallback?.(100);
	}

	const fileRes = await uniCloud.getTempFileURL({
		fileList: uploadResList.map((uploadRes) => uploadRes.fileID)
	});
	if (fileRes.fileList?.length) {
		uploadedCallback(
			fileRes.fileList.map((file, index) => {
				return {
					...file,
					name: tempFiles[index].filename,
					url: file.tempFileURL,
					size: tempFiles[index].size,
					extname: tempFiles[index].extname,
					fileType: 'image'
				};
			})
		);
	}
}
